<?php

namespace app\admin\middleware;

use app\admin\validate\Account as AccountValidate;
use app\lib\exception\Miss;
use app\lib\exception\Parameter;
use think\exception\ValidateException;
use app\model\Account as UserAccount;


class Account
{
    public function handle($request, \Closure $next)
    {
        $params = $request->param();


        //echo'mmm';
        try {
            validate(AccountValidate::class)->scene('login')->check($params);
        } catch (ValidateException $th) {
            // throw new Exception($th->getMessage());
            // return json(['msg'=>$th->getMessage(),'code'=>301]);
            throw new Parameter(
                ['msg' => $th->getMessage()]
            );
        }
        $exist = (new UserAccount())->check($params['username'], $params['password']);
        if (!$exist) {
            throw new Miss(
                [
                    'msg' => '不存在'
                ]
            );
        }
        $params['id'] = $exist['id'];
        $params['scope'] = $exist['scope'];
        $request->params = $params;
        return $next($request);
    }
}
